import 'dart:convert';

import 'package:airbnb_clone/internal/cache/app_cache.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class WebSocketMangeer {
  late WebSocketChannel webSocketChannel;
  Function(dynamic) handFunctoin;
  Function(bool) listenFunction;
  bool socketConnect = false;
  String url = "ws://120.25.126.125:7788/ws/chat";
  WebSocketMangeer({required this.handFunctoin, required this.listenFunction}) {
    _initWebSocket();
  }
  // 初始化链接
  void _initWebSocket() {
    Map<String, dynamic> headers = {"Authorization": AppCache.token};
    webSocketChannel = IOWebSocketChannel.connect(url, headers: headers);
    logPrint("connect url:$url");
    socketConnect = true;
    webSocketChannel.stream.listen((data) {
      handFunctoin(data);
    }, onDone: () {
      socketConnect = false;
      listenFunction(false);
    }, onError: (error) {
      socketConnect = false;
      listenFunction(false);
      logPrint("ws_connect_error: $error");
    }, cancelOnError: true);
  }

  // 发送消息
  void sendMessage(int id, String message) {
    if (socketConnect) {
      String jsonData = jsonEncode({"Receptor": id, "Msg": message});
      webSocketChannel.sink.add(jsonData);
      
    } else {
      logPrint("ws_connect_error: close");
    }
  }

  // 关闭连接
  void closeConnect() {
    socketConnect = false;
    webSocketChannel.sink.close();
  }

  // 日志输出
  void logPrint(dynamic data) {
    // print("\n");
    // print("ws_connect: $data");
    // print("\n");
  }
}
